package com.github.baichuan.network;


import com.github.baichuan.binary.Endian;
import lombok.NonNull;
import org.apache.commons.lang3.math.NumberUtils;

public class IPv4 {
    /**
     * 测试是否IP地址
     * @param ip
     * @return
     */
    public static boolean test(@NonNull String ip){
        String[] numbers = ip.split("\\.");
        if(numbers.length != 4)
            return false;

        for(String number : numbers){
            if(!NumberUtils.isDigits(number)){
                return false;
            }

            Short value = Short.valueOf(number);
            if(value > 255)
                return false;
        }
        return true;
    }

    public static String toString(@NonNull byte[] bytes){
        if(bytes.length != 4){
            throw new IllegalArgumentException("IPv4地址必须为4个字节");
        }
        StringBuilder ip = new StringBuilder();
        for(int i = 0; i< bytes.length; i++){
            ip.append(Endian.BIG.uint8(bytes[i]));
            if(i + 1 < bytes.length){
                ip.append(".");
            }
        }
        return ip.toString();
    }

    public static byte[] toBytes(@NonNull String ip){
        String[] values = ip.split("\\.");
        if(values.length != 4){
            throw new IllegalArgumentException("IPv4地址格式错误：" + ip);
        }
        byte[] bytes = new byte[4];
        for(int i = 0; i<bytes.length; i++){
            int number = Integer.parseInt(values[i]);
            bytes[i] = (byte)number;
        }
        return bytes;
    }
}
